App({
  globalData: {
    userInfo: null,
    token: null,
    role: 'customer', // 默认角色
    baseUrl: 'http://localhost:8000/api' // 后端API基础URL
  },

  onLaunch: function () {
    // 小程序启动时检查登录状态
    this.checkLoginStatus();
  },

  checkLoginStatus: function () {
    // 检查本地存储的token
    const token = wx.getStorageSync('token');
    if (token) {
      this.globalData.token = token;
      // 获取用户信息
      this.getUserInfo();
    }
  },

  getUserInfo: function () {
    wx.request({
      url: `${this.globalData.baseUrl}/auth/userinfo/`,
      header: {
        'Authorization': `Bearer ${this.globalData.token}`
      },
      success: (res) => {
        if (res.statusCode === 200) {
          this.globalData.userInfo = res.data;
          this.globalData.role = res.data.role;
        } else {
          // token过期，清除本地存储
          wx.removeStorageSync('token');
          this.globalData.token = null;
          this.globalData.userInfo = null;
        }
      },
      fail: () => {
        console.error('获取用户信息失败');
      }
    });
  },

  login: function (code, userInfo, callback) {
    wx.request({
      url: `${this.globalData.baseUrl}/auth/wx_login/`,
      method: 'POST',
      data: {
        code: code,
        nickname: userInfo.nickName,
        avatar: userInfo.avatarUrl
      },
      success: (res) => {
        if (res.statusCode === 200) {
          // 保存token到本地存储
          wx.setStorageSync('token', res.data.access);
          this.globalData.token = res.data.access;
          this.globalData.userInfo = res.data.user;
          this.globalData.role = res.data.user.role;
          callback && callback(res.data);
        } else {
          console.error('登录接口返回错误', res);
          wx.showToast({
            title: '登录失败：' + (res.data.error || '未知错误'),
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        console.error('网络请求失败', err);
        wx.showToast({
          title: '网络错误，请检查网络连接',
          icon: 'none'
        });
      }
    });
  },

  // 带手机号的登录方法
  loginWithPhone: function (code, userInfo, encryptedData, iv, callback) {
    wx.request({
      url: `${this.globalData.baseUrl}/auth/wx_login/`,
      method: 'POST',
      data: {
        code: code,
        nickname: userInfo.nickName,
        avatar: userInfo.avatarUrl,
        encrypted_data: encryptedData,
        iv: iv
      },
      success: (res) => {
        if (res.statusCode === 200) {
          // 保存token到本地存储
          wx.setStorageSync('token', res.data.access);
          this.globalData.token = res.data.access;
          this.globalData.userInfo = res.data.user;
          this.globalData.role = res.data.user.role;
          callback && callback(res.data);
        } else {
          console.error('登录接口返回错误', res);
          wx.showToast({
            title: '登录失败：' + (res.data.error || '未知错误'),
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        console.error('网络请求失败', err);
        wx.showToast({
          title: '网络错误，请检查网络连接',
          icon: 'none'
        });
      }
    });
  },

  request: function (options) {
    // 封装带token的请求
    const header = options.header || {};
    if (this.globalData.token) {
      header['Authorization'] = `Bearer ${this.globalData.token}`;
    }
    
    wx.request({
      ...options,
      header: header,
      fail: (err) => {
        if (err.errMsg.includes('401')) {
          // token过期，跳转到登录页
          wx.removeStorageSync('token');
          this.globalData.token = null;
          wx.redirectTo({
            url: '/pages/auth/login'
          });
        }
        options.fail && options.fail(err);
      }
    });
  }
})